package ui;

import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;

import tree.PageNode;
import util.Util;

/**
 * This class displays the text for the current node.
 * @author TKington
 *
 */
public class TextEditorPane extends JEditorPane {
	/** View mode. */
	public static final int TEXTMODE_VIEWHTML = 0;
	/** Edit mode. */
	public static final int TEXTMODE_EDITHTML = 1;
	
	/** The one and only instance */
	private static TextEditorPane instance;
	
	/** The current mode. */
	private int mode;
	
	/** 
	 * Returns the instance.
	 * @return the instance 
	 */
	public static TextEditorPane instance() {
		if(instance == null)
			instance = new TextEditorPane();
		return instance;
	}
	
	/** Creates the single instance */
	private TextEditorPane() {
		super("text/html", "\n");
	}

	/**
	 * Inserts a link to another page at the cursor position.
	 * @param page the PageNode to link to
	 */
	public void insertLink(PageNode page) {
		int pos = getCaretPosition();
		try {
			String link = "<a href=\"node:" + page.getID() + "\">"
						+ "link text</a>";
			getDocument().insertString(pos, link, null);
			Main.frame.setDirty(true);
		}
		catch(BadLocationException e) { Util.log(e); }
	}
	
	/**
	 * Returns the current mode.
	 * @return the current mode
	 */
	public int getMode() { return mode; }
	
	/**
	 * Sets the current mode.
	 * @param mode the new mode
	 */
	public void setMode(int mode) {
		this.mode = mode;
		
		Main.frame.setTextModeCombo(mode);
		
		String contentType = null;
    	switch(mode) {
    	case TEXTMODE_VIEWHTML:
    		contentType = "text/html"; //$NON-NLS-1$
    		break;
    	case TEXTMODE_EDITHTML:
    		contentType = "text/plain"; //$NON-NLS-1$
    		break;
    	}
    	
    	setContentType(contentType);
    	setEditable(mode != TextEditorPane.TEXTMODE_VIEWHTML);
	}
}
